import axios from 'axios';
import { Toast } from 'vant';
import { createStore } from 'vuex';
import router from '../router';

const store = createStore({
  state: {
    name: '张三',
    keepLiveRoute: [],
    userInfo: JSON.parse(localStorage.getItem('SetUserInfo')) || {},
  },
  getters: {},
  mutations: {
    ClearKeep(state) {
      if (state.keepLiveRoute.length > 0) state.keepLiveRoute = [];
      console.log('清空缓存路由！');
    },
    SetKeep(state, routeName) {
      console.log('设置缓存路由！');
      state.keepLiveRoute.indexOf(routeName) == -1 &&
        state.keepLiveRoute.push(routeName);
    },
    RemoveKeep(state, routeName) {
      console.log('移除缓存路由！');
      state.keepLiveRoute.splice(state.keepLiveRoute.indexOf(routeName), 1);
    },
    GetKeep(state) {
      console.log('获取缓存路由！');
      return state.keepLiveRoute;
    },
    SetUserInfo(state, userInfo) {
      console.log(userInfo, 'userInfouserInfouserInfo');
      state.userInfo = userInfo;
    },
  },
  actions: {
    async login({ commit }, user) {
      return new Promise((resolve, reject) => {
        axios({
          method: 'post',
          url: '/pms/api/v1/pmsUser/login?encryptTwice=true',
          headers: {
            isToken: false,
            'Access-Control-Allow-Origin': '*',
          },
          data: {
            account: user.account,
            password: user.password,
            menuCode: user.menuCode,
            captchaKey: '',
          },
        }).then((response) => {
          if (response.data.code == 0) {
            localStorage.setItem('accessToken', response.data.data.accessToken);
            try {
              localStorage.setItem(
                'SetUserInfo',
                JSON.stringify(response.data.data)
              );
            } catch (error) {}
            commit('SetUserInfo', response.data.data);
            resolve(response.data.data);
            console.log(
              response.data.data,
              'response.data.dataresponse.data.dataresponse.data.data'
            );
          } else {
            Toast({
              duration: 1500,
              message: response.data.message,
            });
            reject(response.data.message);
          }
        });
      });
    },

    async getUserInfoByToken({ commit }, accessToken) {
      return new Promise((resolve, reject) => {
        axios({
          method: 'get',
          url: '/pms/api/v1/pmsUser/userinfo',
          headers: {
            Authorization: 'Bearer ' + accessToken,
            'Access-Control-Allow-Origin': '*',
          },
        })
          .then((response) => {
            if (response.data.code == 0) {
              console.log('response.data.data', response.data.data);
              resolve(response.data.data);
            } else {
              Toast({
                duration: 1500,
                message: response.data.message,
              });
              reject(response.data.message);
            }
          })
          .catch((error) => {
            router.push({ path: '/login' });
            reject(error);
          });
      });
    },

    async getPositionsByUserId({ state }, { userId, accessToken }) {
      return new Promise((resolve, reject) => {
        axios({
          method: 'get',
          url: '/pms/api/v1/pmsUser/positions/' + userId,
          headers: {
            Authorization: 'Bearer ' + accessToken,
            'Access-Control-Allow-Origin': '*',
          },
        })
          .then(function (response) {
            if (response.data.code == 0) {
              resolve(response.data.data);
            } else {
              reject(response.data.message);
            }
          })
          .catch((error) => {
            router.push({ path: '/login' });
            reject(error);
          });
      });
    },

    changePosition({ state, commit }, { positionId, accessToken }) {
      return new Promise((resolve, reject) => {
        axios({
          method: 'post',
          url:
            '/pms/api/v1/pmsUser/changePosition/' +
            positionId +
            '?menuCode=goldenStar2',
          headers: {
            Authorization: 'Bearer ' + accessToken,
            'Access-Control-Allow-Origin': '*',
          },
        })
          .then(function (response) {
            if (response.data.code == 0) {
              console.log('changePosition', response.data.data);
              commit('SetUserInfo', response.data.data);
              try {
                localStorage.setItem(
                  'SetUserInfo',
                  JSON.stringify(response.data.data)
                );
              } catch (error) {}
              resolve(response.data.data);
            } else {
              reject(response.data.message);
            }
          })
          .catch((error) => {
            router.push({ path: '/login' });
            reject(error);
          });
      });
    },
  },
});
export default store;
